package biz.ezcom.spring.mvc.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import biz.ezcom.spring.mvc.dao.PersonDao;
import biz.ezcom.spring.mvc.domain.Person;

@Repository
public class PersonDaoImpl implements PersonDao {
	private JdbcTemplate jdbcTemplate;

	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	@Resource
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@Override
	public int insert(Person person) {
		String sql = "insert into person (name,birthday) values(?,?)";
		Object[] args = { person.getName(), person.getBirthday() };
		return jdbcTemplate.update(sql, args);
	}

	@Override
	public int deleteById(int id) {
		String sql = "delete from person where id=?";
		Object[] args = { id };
		return jdbcTemplate.update(sql, args);
	}

	@Override
	public int updateById(Person person) {
		String sql = "update person set name=?,birthday=? where id=?";
		Object[] args = { person.getName(), person.getBirthday(), person.getId() };
		return jdbcTemplate.update(sql, args);
	}

	@Override
	public Person selectById(int id) {
		String sql = "select id,name,birthday from person where id=?";
	    Object[] args = {id};
	    final Person person = new Person();
	    jdbcTemplate.query(sql, args, new RowCallbackHandler() {
	      @Override
	      public void processRow(ResultSet rs) throws SQLException {
	        if (!(rs.isAfterLast())) {
	          person.setId(rs.getInt(1));
	          person.setName(rs.getString(2));
	          person.setBirthday(rs.getDate(3));
	        }
	      }
	    });
	    if (person.getId() == 0) {
	      return null;
	    } else {
	      return person;
	    } 
	}
}
